import Axios from 'axios'
import * as types from '../mutations-types'

const state = {
  wx: window.wx,
  shareConfig: {
    title: '运动数根',
    link: window.location.href,
    desc: '致力于通过图片、文字、视频更形象地展现出赛事效果，积累精致内容。让每个赛事的价值最大化，为用户提供实际的解决方案。',
    imgUrl: 'http://boyubasketball.oss-cn-shanghai.aliyuncs.com/image/fe3f5fc9-625f-4102-8811-9030f6c6caca.jpeg'
  },
  wxReady: false
}
const getters = {
  shareConfig (state) {
    state.shareConfig.link = window.location.href // 初始化当前分享的地址
    return state.shareConfig
  },
  wxReady () {
    return state.wxReady
  },
  wx () {
    return state.wx
  }
}
const mutations = {
  [types.SET_WX_SHARE_CONFIG] (state, val) {
    state.shareConfig = Object.assign({}, state.shareConfig, val)
  },
  [types.SET_WX_READY] (state, val) {
    state.wxReady = val
  }
}
const actions = {
  injectWX: (context, shareConfig) => {
    context.commit(types.SET_WX_SHARE_CONFIG, shareConfig)
    Axios.post('weChatConfig/config', {url: window.location.href.split('#')[0]}).then(rst => {
      let config = rst.data
      let wx = state.wx
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: config.appId, // 必填，公众号的唯一标识
        timestamp: config.timestamp.toString(), // 必填，生成签名的时间戳
        nonceStr: config.nonceStr, // 必填，生成签名的随机串
        signature: config.signature, // 必填，签名，见附录1
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'updateAppMessageShareData']// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      })
      wx.ready(() => {
        context.commit(types.SET_WX_READY, true)
      })
      wx.error(() => {
        context.commit(types.SET_WX_READY, false)
      })
    })
  },
  // https://www.oudahe.com/p/46395/
  updateConfig: (context, shareConfig) => {
    context.commit(types.SET_WX_SHARE_CONFIG, shareConfig)
  }
}
export default {
  state,
  getters,
  mutations,
  actions
}
